<?php

namespace App\Models;


use App\Observers\Contract\ObserverCleanable;
use App\Observers\OSSCleanObserver;
use App\Services\Locale\AppLanguage;
use App\Services\Utils\OSSable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

/**
 * Class Device - 设备
 *
 * @property int $luminance_min
 * @property int $luminance_max
 * @property int $color_temperature_min
 * @property int $color_temperature_max
 * @package App\Models
 */
class Device extends Model implements ObserverCleanable
{
    use OSSable;

    protected $table = 'devices';

    protected static $unguarded = true;

    const IS_SHOW = 1;

    protected $casts = [
        'sort_order'            => 'int',
        'manufacture_id'        => 'int',
        'color_temperature'     => 'int',
        'luminance'             => 'int',
        'is_show'               => 'int',
        'luminance_min'         => 'int',
        'luminance_max'         => 'int',
        'color_temperature_min' => 'int',
        'color_temperature_max' => 'int',
        'price'                 => 'float',
    ];

    protected $product_img_key_prefix = 'device/product_img/';

    /**
     * @return hasMany
     */
    public function deviceDescriptions(): hasMany
    {
        return $this->hasMany(DeviceDescription::class, 'device_id', 'id');
    }

    /**
     * 对应请求的多语言描述
     *
     * @return hasOne
     */
    public function localeDescription(): hasOne
    {
        return $this->hasOne(DeviceDescription::class, 'device_id', 'id')
            ->where('language_id', AppLanguage::getLanguageIdFromAppLocale());
    }

    /**
     * @param $product_img
     *
     * @return void
     * @throws \Exception
     */
    public function setProductImgAttribute($product_img): void
    {
        if (is_file($product_img)) {
            $new_product_img = $this->uploadPostFile($product_img, $this->product_img_key_prefix);
            $this->attributes['product_img'] = $new_product_img;
        } else if (is_string($product_img) && strlen($product_img)) {
            $this->attributes['product_img'] = $product_img;
        }
    }

    /**
     * @return string|null
     * @throws \Exception
     */
    public function getProductImgAttribute(): ?string
    {
        return $this->attributeToStaticUrl('product_img');
    }

    /**
     * @return array
     */
    public function keyCleanColumns(): array
    {
        return ['product_img'];
    }

    /**
     * 注册删除 bosKey 事件绑定
     */
    protected static function boot()
    {
        parent::boot();

        /**
         * 监听bos清理事件
         */
        self::observe(OSSCleanObserver::class);
    }
}
